import Vue from 'vue'
import VueRouter from 'vue-router'
import Films from '@/views/Films.vue'
import Cinema from '@/views/Cinemas.vue'
import Center from '@/views/Center.vue'
import Nowplaying from '@/views/films-children/Nowplaying.vue'
import Comingsonn from '@/views/films-children/Comingsoon.vue'
import Search from '@/views/Search'
import Detail from '@/views/Detail'
import City from '@/views/City'
// import Order from '@/views/Order'
import Login from '@/views/Login'

Vue.use(VueRouter)

// 反向代理在vue.config.js  devServer
const routes = [{
        path: '/films',
        component: Films,
        // 嵌套路由,
        children: [{
                path: '/films/nowplaying',
                component: Nowplaying,
            },
            {
                path: '/films/commingsoon',
                component: Comingsonn,
            },
            {
                path: '/films',
                redirect: '/films/nowplaying'
            }
        ],
    },
    {
        path: '/center',
        component: Center,
        meta: {
            judge: true
        }
    },
    {
        path: '/order',
        // 路由懒加载   到对应的路径才开始下载相对应所需要的的资源，然后上面的import要注释掉，要不然没啥用 
        component: () =>
            import ('@/views/Order'),
        meta: {
            judge: true
        },
        // 局部路由
        // beforeEnter: (to, from, next) => {
        //     if (localStorage.getItem('user')) {
        //         next()
        //     } else {
        //         next({
        //             path: '/login',
        //             query: {
        //                 redirect: to.fullPath
        //             }
        //         })
        //     }
        // }
    },
    {
        path: '/cinema',
        component: Cinema
    },
    {
        path: '/city',
        component: City
    },
    {

        name: 'detailName', // 命名路由
        path: '/detail/:id', // 动态路由
        component: Detail
    },
    {
        path: '/cinema/search',
        component: Search
    },
    {
        path: '/login',
        component: Login
    },
    // 重定向功能，当搜索完整为斜杠的时候，直接转到path:'/films'链接
    //  paht:'*' 就是通配所有，一旦出现上面没有的情况，那就全部默认跑到films,但是这个要放到最末尾，要不然会直接默认主页
    {
        path: '*',
        redirect: '/films'
    }
]

const router = new VueRouter({
    // 当mode 为hash路由路径就有#号,history就没有， 默认为hash
    mode: 'history',
    routes
})

// 全局路由     第一个参数显示是到哪去，第二个是从哪来，第三个是跳转验证
router.beforeEach((to, from, next) => {
    // console.log(to)
    if (to.meta.judge == true) {
        if (localStorage.getItem('user')) {
            next()
        } else {
            next({
                path: '/login',
                // 这边的query 可以理解成就是你从其他页面跳转到的登录，然后你登录完后就可以跳回之前页面
                //  login?redirect=%2Fcenter 相当于这样，然后再从登录那边拿到局部路由就可以拿到这个redirect，从而返回登录之前页面
                query: {
                    redirect: to.fullPath
                }
            })
        }
        // next('/login')
    } else {
        next()
    }
})

export default router